"""
🐂 牛马工时日志汇报系统 - Streamlit Web应用
智能AI驱动的工时数据分析与汇报系统
"""

import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta
import time
import requests
from typing import List, Dict, Optional
from strings import CACHE_TTL, STREAMLIT_STYLE, API_BASE_URL
from utils.logger import logger
from utils.tools import generate_report_filename, markdown_to_html
from streamlit_requests import get_frameworks, get_projects, get_report_data

# 页面配置
st.set_page_config(
    page_title="牛马工时日志汇报系统",
    page_icon="🐂",
    layout="wide",
    initial_sidebar_state="expanded"
)

# 自定义CSS样式
st.markdown(STREAMLIT_STYLE, unsafe_allow_html=True)

# 主标题
st.markdown("""
<div class="main-header">
    <h1>🐂 牛马工时日志汇报系统</h1>
</div>
""", unsafe_allow_html=True)

# 创建主要的Tab布局
tab1, tab2 = st.tabs(["📊 固定查询", "🧠 Chatbot查询"])

# ===================== Tab1: 固定查询 =====================
with tab1:
    # 侧边栏查询条件
    with st.sidebar:
        st.markdown("### 🔍 查询条件")
        
        # 员工姓名
        st.markdown("#### 👤 员工姓名")
        employee_name = st.text_input(
            "输入员工姓名",
            placeholder="支持模糊搜索...",
            help="从员工列表中搜索匹配的姓名"
        )
        
        # 部门选择
        st.markdown("#### 🏢 部门选择")
        
        # 获取部门数据
        frameworks_data = get_frameworks()
        if frameworks_data:
            # 显示部门统计信息
            # st.caption(f"📊 共找到 {len(frameworks_data)} 个部门")
            
            department_options = ["全部部门"] + [item['FrameworkName'] for item in frameworks_data]
            department = st.selectbox(
                "选择部门",
                options=department_options,
                help="选择要查询的部门"
            )
            # 存储部门ID映射（用于后续API调用）
            if department != "全部部门":
                selected_dept = next((item for item in frameworks_data if item['FrameworkName'] == department), None)
                if selected_dept:
                    st.session_state['selected_dept_id'] = selected_dept['id']
        else:
            st.warning("⚠️ 无法获取部门信息，请检查API服务是否正常运行")
            department = st.selectbox(
                "选择部门",
                options=["全部部门"],
                help="API服务不可用，请稍后重试"
            )
        
        # 项目选择
        st.markdown("#### 📁 项目名称")
        
        # 获取项目数据
        projects_data = get_projects()
        if projects_data:
            # 显示项目统计信息
            # st.caption(f"📊 共找到 {len(projects_data)} 个项目")
            
            # 格式化项目选项：显示项目名称、ID和状态
            project_options = ["全部项目"] + [
                f"{item['ProjectName']} ({item['ProjectId']}) - {item.get('Project', '未知状态')}" 
                for item in projects_data
            ]
            selected_project = st.selectbox(
                "选择项目",
                options=project_options,
                help="支持输入搜索项目名称或ID，在下拉框中输入关键字即可过滤"
            )
            
            # 存储项目信息（用于后续API调用）
            if selected_project != "全部项目":
                # 从显示文本中提取项目ID
                project_id_part = selected_project.split(" (")[1].split(")")[0]
                selected_proj = next((item for item in projects_data if item['ProjectId'] == project_id_part), None)
                if selected_proj:
                    st.session_state['selected_project'] = selected_proj
                    # 显示项目详细信息
                    st.caption(f"📋 项目类型: {selected_proj.get('ProjectType', '未知')} | 状态: {selected_proj.get('Project', '未知')}")
            else:
                st.session_state['selected_project'] = None
        else:
            st.warning("⚠️ 无法获取项目信息，请检查API服务是否正常运行")
            selected_project = st.selectbox(
                "选择项目",
                options=["全部项目"],
                help="API服务不可用，请稍后重试"
            )
        
        # 时间范围
        st.markdown("#### 📅 时间范围")
        
        # 获取默认值（支持快捷选项设置）
        default_start = st.session_state.get('start_date', datetime.now() - timedelta(days=7))
        default_end = st.session_state.get('end_date', datetime.now())
        
        # 转换为date对象
        if hasattr(default_start, 'date'):
            default_start = default_start.date()
        elif isinstance(default_start, datetime):
            default_start = default_start.date()
            
        if hasattr(default_end, 'date'):
            default_end = default_end.date()
        elif isinstance(default_end, datetime):
            default_end = default_end.date()
        
        col1, col2 = st.columns(2)
        with col1:
            start_date = st.date_input(
                "开始日期",
                value=default_start,
                help="查询开始日期"
            )
        with col2:
            end_date = st.date_input(
                "结束日期",
                value=default_end,
                help="查询结束日期"
            )
        
        # 用户手动修改日期时，清除session state
        if 'start_date' in st.session_state:
            stored_start = st.session_state['start_date']
            if isinstance(stored_start, datetime):
                stored_start = stored_start.date()
            if start_date != stored_start:
                del st.session_state['start_date']
        
        if 'end_date' in st.session_state:
            stored_end = st.session_state['end_date'] 
            if isinstance(stored_end, datetime):
                stored_end = stored_end.date()
            if end_date != stored_end:
                del st.session_state['end_date']
        
        # 时间范围验证
        if start_date and end_date:
            date_diff = (end_date - start_date).days
            
            # 判断查询类型和时间限制
            has_department = department and department != "全部部门"
            has_project = st.session_state.get('selected_project') is not None
            has_employee = employee_name and employee_name.strip()
            
            # 确定时间限制
            if has_department or has_project:
                max_days = 14
                query_type = "部门/项目查询"
            elif has_employee:
                max_days = 30
                query_type = "员工查询"
            else:
                max_days = 14  # 默认限制
                query_type = "通用查询"
            
            # 显示时间范围状态
            if date_diff < 0:
                st.error("❌ 结束日期不能早于开始日期")
            elif date_diff > max_days:
                st.error(f"❌ {query_type}时间范围不能超过{max_days}天，当前选择了{date_diff}天")
                st.info(f"💡 建议：请调整时间范围到{max_days}天以内")
            # else:
            #     st.success(f"✅ 时间范围：{date_diff}天 ({query_type}，最多{max_days}天)")
        else:
            st.warning("⚠️ 请选择完整的时间范围")
        
        # 快捷选项
        st.markdown("#### ⚡ 快捷选项")
        
        # 根据当前查询类型确定可用的快捷选项
        has_department = department and department != "全部部门"
        has_project = st.session_state.get('selected_project') is not None
        has_employee = employee_name and employee_name.strip()
        
        if has_department or has_project:
            max_days = 14
        elif has_employee:
            max_days = 30
        else:
            max_days = 14
        
        quick_options = st.columns(2)
        with quick_options[0]:
            if st.button("本周", help="最近7天"):
                # 设置最近7天
                st.session_state['start_date'] = (datetime.now() - timedelta(days=7)).date()
                st.session_state['end_date'] = datetime.now().date()
                st.rerun()
            
            if st.button("最近14天", help="最近14天" if max_days >= 14 else "当前查询类型不支持14天", 
                        disabled=max_days < 14):
                if max_days >= 14:
                    st.session_state['start_date'] = (datetime.now() - timedelta(days=14)).date()
                    st.session_state['end_date'] = datetime.now().date()
                    st.rerun()
                    
        with quick_options[1]:
            if st.button("最近30天", help="最近30天" if max_days >= 30 else "当前查询类型不支持30天", 
                        disabled=max_days < 30):
                if max_days >= 30:
                    st.session_state['start_date'] = (datetime.now() - timedelta(days=30)).date()
                    st.session_state['end_date'] = datetime.now().date()
                    st.rerun()
                    
            if st.button("本季度", disabled=True, help="本季度查询暂不可用"):
                st.warning("⚠️ 本季度查询暂不可用")
        
        # 动态显示当前的时间范围限制
        current_has_department = department and department != "全部部门"
        current_has_project = st.session_state.get('selected_project') is not None
        current_has_employee = employee_name and employee_name.strip()
        
        if current_has_department or current_has_project:
            current_limit = "14天"
            current_type = "部门/项目查询"
        elif current_has_employee:
            current_limit = "30天"
            current_type = "员工查询"
        else:
            current_limit = "14天"
            current_type = "通用查询"
        
        st.caption(f"📋 当前查询类型：{current_type}，时间限制：{current_limit}")
        
        # 操作按钮区域
        st.markdown("---")
        
        # 检查时间范围是否有效
        time_range_valid = False
        if start_date and end_date:
            date_diff = (end_date - start_date).days
            has_department = department and department != "全部部门"
            has_project = st.session_state.get('selected_project') is not None
            has_employee = employee_name and employee_name.strip()
            
            if has_department or has_project:
                max_days = 14
            elif has_employee:
                max_days = 30
            else:
                max_days = 14
            
            time_range_valid = date_diff >= 0 and date_diff <= max_days
        
        # 并排显示按钮
        button_col1, button_col2 = st.columns(2)
        
        with button_col1:
            refresh_clicked = st.button(
                "🔄 刷新数据", 
                help="刷新部门和项目数据",
                use_container_width=True
            )
        
        with button_col2:
            generate_report = st.button(
                "🎯 生成报告",
                type="primary",
                help="点击生成工时报告" if time_range_valid else "请先调整时间范围到允许的范围内",
                disabled=not time_range_valid,
                use_container_width=True
            )
        
        # 处理刷新按钮点击
        if refresh_clicked:
            st.cache_data.clear()
            # 清除报告相关的session state
            if 'report_data' in st.session_state:
                del st.session_state['report_data']
            if 'query_params' in st.session_state:
                del st.session_state['query_params']
            if 'report_generated' in st.session_state:
                del st.session_state['report_generated']
            st.rerun()
    
    # 主内容区域
    # 检查是否有已生成的报告数据
    report_data = st.session_state.get('report_data')
    query_params = st.session_state.get('query_params')
    report_generated = st.session_state.get('report_generated', False)
    
    if generate_report or report_generated:
        # 如果是新生成报告，清除旧数据
        if generate_report:
            # 清除旧的报告数据
            if 'report_data' in st.session_state:
                del st.session_state['report_data']
            if 'query_params' in st.session_state:
                del st.session_state['query_params']
            if 'report_generated' in st.session_state:
                del st.session_state['report_generated']
        
        # 准备查询参数
        selected_project_info = st.session_state.get('selected_project')
        query_params = {
            "people_name": employee_name if employee_name else None,
            "framework_name": department if department != "全部部门" else None,
            "project_id": selected_project_info['ProjectId'] if selected_project_info else None,
            "start_date": start_date.strftime("%Y-%m-%d"),
            "end_date": end_date.strftime("%Y-%m-%d")
        }
        
        # 显示查询参数调试信息（开发阶段）
        if st.checkbox("🔍 显示查询参数", help="开发调试用"):
            st.json(query_params)
        
        # 只有在生成新报告时才调用API
        if generate_report:
            with st.spinner("正在生成报告..."):
                # 调用API获取报告数据
                report_data = get_report_data(query_params)
            
            if report_data:
                st.success("✅ 报告生成完成！")
                
                # 存储报告数据到session state
                st.session_state['report_data'] = report_data
                st.session_state['query_params'] = query_params
                st.session_state['report_generated'] = True
            else:
                st.error("❌ 报告生成失败，请检查查询条件或稍后重试")
                st.stop()
        else:
            # 使用已存储的报告数据
            report_data = st.session_state.get('report_data')
            if not report_data:
                st.error("❌ 报告数据丢失，请重新生成报告")
                st.stop()
        
        # 汇总统计卡片
        st.markdown("### 📊 汇总统计")
        col1, col2, col3, col4 = st.columns(4)
        
        # 从报告数据中获取统计信息
        total_hours = report_data.get('total_hours', 0)
        total_records = report_data.get('total_records', 0)
        
        # 计算涉及人员和项目数量
        details = report_data.get('details', [])
        people_set = set()
        project_set = set()
        for detail in details:
            if detail.get('PeopleName'):
                people_set.add(detail['PeopleName'])
            if detail.get('ProjectName'):
                project_set.add(detail['ProjectName'])
        
        with col1:
            st.metric(
                label="总工时",
                value=f"{total_hours:.1f}小时",
                delta="",
                help="统计时间段内的总工时数"
            )
        
        with col2:
            st.metric(
                label="查询时间段",
                value=f"{(end_date - start_date).days}天",
                delta="",
                help="本次查询的时间范围"
            )
        
        with col3:
            st.metric(
                label="涉及人员",
                value=f"{len(people_set)}人",
                delta="",
                help="参与工作的员工数量"
            )
        
        with col4:
            st.metric(
                label="涉及项目",
                value=f"{len(project_set)}个",
                delta="",
                help="涉及的项目数量"
            )
        
        # AI智能总结
        st.markdown("### 🤖 AI智能总结")
        
        # 获取AI生成的总结
        summary = report_data.get('summary', '暂无总结内容')
        
        # 下载HTML报告按钮
        if summary and summary != '暂无总结内容':
            # 使用列布局，让下载按钮不影响页面状态
            download_col1, download_col2 = st.columns([1, 3])
            
            with download_col1:
                # 生成HTML内容
                html_content = markdown_to_html(summary)
                
                # 生成文件名
                filename = generate_report_filename(
                    query_params, 
                    start_date.strftime("%Y-%m-%d"), 
                    end_date.strftime("%Y-%m-%d")
                )
                
                # 下载按钮
                st.download_button(
                    label="📄 下载HTML报告",
                    data=html_content,
                    file_name=filename,
                    mime="text/html",
                    help="下载包含完整样式的HTML格式报告",
                    use_container_width=True
                )
        
        with st.expander("📝 详细总结内容", expanded=True):
            st.markdown(f"""
            <div class="ai-summary">
                {summary}
            </div>
            """, unsafe_allow_html=True)
        
        # 数据可视化
        st.markdown("### 📈 数据可视化")
        chart_col1, chart_col2 = st.columns(2)
        
        with chart_col1:
            st.markdown("#### 工时分布图")
            if details:
                # 按部门统计工时
                dept_hours = {}
                for detail in details:
                    dept = detail.get('FrameworkName', '未知部门')
                    hours = detail.get('WorkHour', 0)
                    dept_hours[dept] = dept_hours.get(dept, 0) + hours
                
                if dept_hours:
                    pie_data = pd.DataFrame([
                        {'部门': dept, '工时': hours} 
                        for dept, hours in dept_hours.items()
                    ])
                    fig_pie = px.pie(
                        pie_data, 
                        values='工时', 
                        names='部门',
                        title='按部门工时分布',
                        color_discrete_sequence=['#8B4513', '#A0522D', '#CD853F', '#DEB887']
                    )
                    st.plotly_chart(fig_pie, use_container_width=True)
                else:
                    st.info("📊 暂无部门工时数据")
            else:
                st.info("📊 暂无数据")
        
        with chart_col2:
            st.markdown("#### 工时趋势图")
            if details:
                # 按日期统计工时
                date_hours = {}
                for detail in details:
                    create_time = detail.get('LogTime')
                    if create_time:
                        # 处理时间格式
                        if isinstance(create_time, str):
                            try:
                                date_str = create_time.split('T')[0]  # 提取日期部分
                                hours = detail.get('WorkHour', 0)
                                date_hours[date_str] = date_hours.get(date_str, 0) + hours
                            except Exception as e:
                                logger.error(f"处理时间格式时发生错误: {e}")
                                continue
                
                if date_hours:
                    trend_data = pd.DataFrame([
                        {'日期': date, '工时': hours} 
                        for date, hours in sorted(date_hours.items())
                    ])
                    fig_line = px.line(
                        trend_data, 
                        x='日期', 
                        y='工时',
                        title='工时趋势',
                        color_discrete_sequence=['#8B4513']
                    )
                    st.plotly_chart(fig_line, use_container_width=True)
                else:
                    st.info("📈 暂无时间趋势数据")
            else:
                st.info("📈 暂无数据")
        
        # 详细数据表格
        st.markdown("### 📋 详细数据表格")
        
        if details:
            # 转换数据格式用于显示
            table_data = []
            for detail in details:
                table_data.append({
                    '姓名': detail.get('PeopleName', '--'),
                    '部门': detail.get('FrameworkName', '--'),
                    '项目': detail.get('ProjectName', '--'),
                    '工时': detail.get('WorkHour', 0),
                    '类型': detail.get('WorkHourType', '--'),
                    '日期': detail.get('LogTime', '--')[:10] if detail.get('LogTime') else '--',
                    '工作内容': detail.get('LogText', '--')[:50] + '...' if detail.get('LogText') and len(detail.get('LogText', '')) > 50 else detail.get('LogText', '--')
                })
            
            # 创建DataFrame
            df = pd.DataFrame(table_data)
            
            # 显示数据表格
            st.dataframe(
                df,
                use_container_width=True,
                height=400
            )
            
            # 导出功能
            export_col1, export_col2, export_col3 = st.columns([1, 1, 2])
            with export_col1:
                st.download_button(
                    label="📥 导出CSV",
                    data=df.to_csv(index=False, encoding='utf-8-sig'),
                    file_name=f"工时报告_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
                    mime="text/csv"
                )
            
            with export_col2:
                # 注意：这里实际应该导出Excel格式，但为了简化使用CSV
                st.download_button(
                    label="📊 导出Excel",
                    data=df.to_csv(index=False, encoding='utf-8-sig'),
                    file_name=f"工时报告_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx",
                    mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                )
        else:
            st.info("📋 暂无详细数据")
            
            # 导出功能（禁用）
            export_col1, export_col2, export_col3 = st.columns([1, 1, 2])
            with export_col1:
                st.button("📥 导出CSV", disabled=True, help="暂无数据可导出")
            
            with export_col2:
                st.button("📊 导出Excel", disabled=True, help="暂无数据可导出")
    
    else:
        # 未生成报告时的默认显示
        st.markdown("""
        <div class="placeholder-content">
            <h3>👋 欢迎使用牛马工时日志汇报系统</h3>
            <p>请在左侧设置查询条件，然后点击"生成报告"按钮开始分析</p>
            <p>📊 支持多维度查询：员工、部门、项目、时间范围</p>
            <p>🤖 AI智能分析：自动生成工时总结和洞察</p>
            <p>📈 数据可视化：直观展示工时分布和趋势</p>
        </div>
        """, unsafe_allow_html=True)

# ===================== Tab2: Chatbot查询 =====================
with tab2:
    # Chatbot查询页面，直接渲染HTML内容
    st.markdown(
        '''
        <div class="placeholder-content">
            <h2>🤖 智能对话查询</h2>
            <h3> @苗艺萌  @郑佳彤 交给你们了</h3>
            <p> 关于这部分的实现，请查看CHATBOT.md</p>
            <div style="margin: 2rem 0;">
                <h3>💬 即将实现的功能：</h3>
                <ul style="text-align: left; display: inline-block;">
                    <li>📝 自然语言工时查询</li>
                    <li>🤖 智能问答对话</li>
                    <li>🔍 上下文相关的工时分析</li>
                    <li>📊 个性化报告生成</li>
                </ul>
            </div>
            <div style="margin: 2rem 0;">
                <h3>🔮 未来功能预览：</h3>
                <div style="background: #f0f8ff; padding: 1rem; border-radius: 8px; margin: 1rem 0;">
                    <p><strong>💬 "帮我查看张三上个月的工时情况"</strong></p>
                    <p><strong>📊 "技术部门本季度加班最多的项目是什么？"</strong></p>
                    <p><strong>📈 "生成一份包含所有部门工时对比的报告"</strong></p>
                </div>
            </div>
            <div style="margin: 2rem 0;">
                <h3>📝 敬请期待...</h3>
                <p>此功能正在开发中，将提供更智能的交互体验</p>
            </div>
        </div>
        ''',
        unsafe_allow_html=True
    )

# 页面底部信息
st.markdown("---")

# 底部图片居中显示
col1, col2, col3 = st.columns([1, 1, 1])
with col2:
    st.image("assets/favicon.png", use_container_width=False)

st.markdown("""
<div style="text-align: center; color: #666; margin-top: 2rem;">
    <p>🐂 牛马工时日志汇报系统 | 基于Streamlit + FastAPI + Deepseek-V3</p>
    <p>最后更新时间: 2025年7月</p>
</div>
""", unsafe_allow_html=True) 